package com.zhang.yygh.user.service.impl;

import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.acl.User;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.yygh.common.exception.YYGHException;
import com.zhang.yygh.common.utils.JwtHelper;
import com.zhang.yygh.user.mapper.PatientMapper;
import com.zhang.yygh.user.mapper.UserInfoMapper;
import com.zhang.yygh.user.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zhang
 * @since 2022-03-10
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private PatientMapper patientMapper;

    //用户登录
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String openid = loginVo.getOpenid();


        //1.获取用户的手机号和验证码
        String phone=loginVo.getPhone();
        String code = loginVo.getCode();
        //2.对用户的手机号和验证码进行非空校验
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            throw new YYGHException(20001,"用户信息有误");
        }
        //TODO:将用户输入的验证码和redis中的验证码做一个比对
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isEmpty(redisCode)||!redisCode.equals(code)){
            throw new YYGHException(20001,"验证码有误");
        }
        UserInfo userInfo=null;
        //openid为空:单纯的手机号登录
        if (StringUtils.isEmpty(openid)){
            //3.确定用户是否是首次登录，是首次登陆，则需要注册一份
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",phone);

            userInfo = baseMapper.selectOne(queryWrapper);
            if (userInfo==null){ //是首次登录，则需要注册一份
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }


        }else {
            UserInfo userInfoFinal = new UserInfo();
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",phone);

            userInfo = baseMapper.selectOne(queryWrapper);
            if (userInfo!=null){ //如果不为空，将内容复制到相应属性中，并把该条记录删除
                BeanUtils.copyProperties(userInfo,userInfoFinal);
                baseMapper.deleteById(userInfo.getId());
            }else {
                userInfoFinal.setPhone(phone);
            }

            //openid不为空:微信绑定手机号登录
            QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("openid",openid);
            userInfo = baseMapper.selectOne(queryWrapper1);
            //userInfo.setPhone(phone);
            userInfoFinal.setOpenid(openid);
            userInfoFinal.setNickName(userInfo.getNickName());
            userInfoFinal.setId(userInfo.getId());
            baseMapper.updateById(userInfoFinal);
        }

        //4.验证用户的状态是否被锁定：被锁定，抛出异常
        if (userInfo.getStatus()==0){
            throw new YYGHException(20001,"用户被锁定");
        }

        //5.返回给页面用户信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            //用微信昵称作为名字
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            //用手机号作为名字
            name = userInfo.getPhone();
        }
        map.put("name", name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }

    //根据当前用户id查询用户信息
    @Override
    public UserInfo selectById(Long userId) {
        UserInfo userInfo1 = baseMapper.selectById(userId);
        Integer authStatus = userInfo1.getAuthStatus();
        //通过枚举类获取认证状态
        String status = AuthStatusEnum.getStatusNameByStatus(authStatus);
        userInfo1.getParam().put("authStatusString",status);
        return userInfo1;
    }

    @Override
    public void saveUserAuthInfo(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);

        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        baseMapper.updateById(userInfo);
    }

    //带查询条件的分页
    @Override
    public Page<UserInfo> getUserInfoPageByQueryCondition(Integer pageNum, Integer limit, UserInfoQueryVo userInfoQueryVo) {
        Page<UserInfo> page=new Page<UserInfo>(pageNum,limit);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        String keyword = userInfoQueryVo.getKeyword(); //用户名称或者手机号
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        if (!StringUtils.isEmpty(keyword)){
            queryWrapper.like("name",keyword).or().eq("phone",keyword);
        }
        if(!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            queryWrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            queryWrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            queryWrapper.le("create_time",createTimeEnd);
        }
        baseMapper.selectPage(page,queryWrapper);
        page.getRecords().parallelStream().forEach(item->{
            this.packageUserInfo(item);
        });

        return page;
    }

    //编号变成对应值封装
    private void packageUserInfo(UserInfo item) {
        //处理认证状态编码
        item.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(item.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = item.getStatus().intValue()==0 ?"锁定" : "正常";
        item.getParam().put("statusString",statusString);
//        return item;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    //查看用户详情
    @Override
    public Map<String, Object> show(Integer id) {
        Map<String, Object> map = new HashMap<>();
        //1.先查询用户
        UserInfo userInfo = baseMapper.selectById(id);
        map.put("userInfo",userInfo);
        //2.查询用户下面的就诊人信息
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        List<Patient> patientList = patientMapper.selectList(queryWrapper);
        map.put("patientList",patientList);
        return map;
    }

    //认证审批  2通过  -1不通过
    @Override
    public void approval(Long userId, Integer authStatus) {
        //当用户认证状态为2或者-1时才做修改
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }
}
